# -*- coding:utf-8 -*-
from flask import Flask, render_template, request, flash
from .forms import JokeForm
from ..models import Joke, Tag
from . import main
from .. import db

import random
app = Flask(__name__)

@main.route("/")
def index():
    joke_all = Joke.query.all()
    joke_all_len = len(joke_all)
    joke_first = random.randint(1, joke_all_len)
    joke = Joke.query.filter_by(id=joke_first).first_or_404()
    return render_template('index.html', joke=joke)


@main.route("/postjoke", methods=['GET', 'POST'])
def postjoke():
    form = JokeForm()
    if form.validate_on_submit():
        tag_names = form.tags.data
        tag_name_list = tag_names.split('#')
        joke = Joke(
            body=form.body.data
        )
        tag_list = []
        for tmp in tag_name_list:
            tag = Tag.query.filter_by(name=tmp).first()
            if tag is None:
                tag = Tag()
                tag.name = tmp
                db.session.add(tag)
                db.session.commit()
            tag_list.append(tag)
        joke.tags = tag_list
        db.session.add(joke)
        db.session.commit()
        flash('笑话提交成功.')
    return render_template('postjoke.html', form=form)

if __name__ == "__main__":
    app.run(debug=True)